<script setup>
import { onMounted, ref, reactive, toRaw } from "vue";
import { userlist, useroperate, usergetone, userdelet } from "@/api/index.js";
import mangocrud from "@/components/magnxo_crud/index.vue";
import msggage from "@/utils/ActionMessage.js";
import dayjs from "dayjs";
import searchForm from "@/components/searchForm/index.vue";
import AutoNavi from "@/components/AutoNavi/index.vue";
onMounted(() => {
  getUserList();
});
let tableData = ref([]);
let modelRef = reactive({
  lng: 39.909135,
  lat: 116.397417,
});
let keyword = ref("");
let AutoNaviref = ref(null);
let random = ref(Math.random());
let dialogVisible = ref(false);
let mangoref = ref(null);
const ruleFormRef = ref();
const searchFormref = ref();
/**
 * searchForm搜索框 可以插槽
 * operatebtn表格操作
 * columns表格数据项 可以定义插槽
 */
const list = {
  showselection: true,
  showindex: true,
  searchForm: {
    toolbars: [{ key: "search" }, { key: "reset", label: "重置" }],
    forms: [
      { prop: "userName", label: "姓名" },
      { prop: "userEmail", label: "邮箱" },
      {
        prop: ["startime", "endtime"],
        value: ["2022-07-01", "2022-07-02"],
        label: "邮箱",
        fieldType: "daterange",
      },
      {
        prop: "select",
        label: "选择",
        fieldType: "select",
        options: [{ value: "1", label: "1" }],
        labelWidth: 90,
      },
    ],
  },
  operatebtn: [
    { key: "add", label: "添加", type: "primary" },
    { key: "delet", label: "删除", type: "danger" },
  ],
  columns: [
    {
      label: "用户ID",
      property: "userId",
    },
    { label: "用户名", property: "userName" },
    { label: "用户邮箱", property: "userEmail" },
    { label: "用户角色", property: "job" },
    { label: "用户状态", property: "state" },
    {
      label: "注册时间",
      property: "createTime",
      formatter(row, scope, value) {
        return dayjs(value).format("YYYY-MM-DD HH:mm:ss");
      },
    },
    {
      label: "最后登录时间",
      property: "lastLoginTime",
      formatter(row, scope, value) {
        return dayjs(value).format("YYYY-MM-DD HH:mm:ss");
      },
    },
    { label: "操作", slotName: "tool" },
  ],
  pagination: {
    limit: 10,
    page: 1,
    totalKey: 0,
  },
};
const ruleForm = reactive({
  userName: "",
  userEmail: "",
  mobile: "",
  userPwd: "",
  action: "add",
  deptId: [],
  userId: "",
});
const userlistConfig = {
  searchForm: {
    forms: [
      {
        prop: "userName",
        value: null,
        cols: 20,
        label: "姓名",
        rules: [{ required: true, message: "请输入姓名", trigger: "blur" }],
      },
      {
        prop: "userEmail",
        value: null,
        label: "邮箱",
        cols: 20,
        rules: [{ required: true, message: "请输入邮箱", trigger: "blur" }],
      },
      {
        prop: "mobile",
        value: null,
        label: "手机号",
        cols: 20,
        rules: [{ required: true, message: "请输入手机号", trigger: "blur" }],
      },
      {
        prop: "userPwd",
        value: null,
        label: "密码",
        cols: 20,
        fieldType: "psw",
        rules: [{ required: true, message: "请输入密码", trigger: "blur" }],
      },
    ],
  },
};
let listConfig = reactive(list);
let userlistCon = reactive(userlistConfig);
const getUserList = async (params) => {
  await userlist(params).then((res) => {
    if (res.code !== 200) {
      return;
    } else {
      tableData.value = res.data.list;
    }
  });
  listConfig.pagination.totalKey = tableData.value.length;
};
const toolFn = (scope) => {
  ruleForm.action = "edit";
  usergetone({ userName: scope.row.userName }).then((res) => {
    random.value = Math.random();
    const object = res.data;
    for (const key in object) {
      if (Object.hasOwnProperty.call(object, key)) {
        const element = object[key];
        userlistCon.searchForm.forms.map((item) => {
          if (key == item.prop) {
            item.value = element;
          }
        });
      }
    }
    Object.assign(ruleForm, res.data);
    dialogVisible.value = true;
  });
};
const deletUser = (ids) => {
  if (ids) {
    let id = [];
    toRaw(ids).map((item) => {
      id.push(item.userId);
    });
    userdelet({ userIds: id });
    getUserList();
  }
};
const submitForm = async () => {
  let params = {};
  searchFormref.value.getParams((error, formParams) => {
    if (!error) {
      params = formParams;
      Object.assign(ruleForm, params);
      useroperate(ruleForm).then((res) => {
        if (res.code !== 200) {
          msggage.warning(res.msg);
        } else {
          msggage.success(res.msg);
          dialogVisible.value = false;
          getUserList();
        }
      });
    }
  });
};
const search = () => {
  let params = mangoref.value.getParams() || {};
  getUserList(params);
};
const reset = () => {
  mangoref.value.resetSearchForm();
};
const add = () => {
  dialogVisible.value = true;
  searchFormref?.value?.resetSearchForm();
  ruleForm.action = "add";
  setTimeout(() => {
    AutoNaviref?.value?.init();
  }, 0);
};
const paginationchange = (page) => {
  msggage.success(page);
  listConfig.pagination.limit = page["limit"];
  listConfig.pagination.page = page["page"];
};
const handleAction = (command, position, selection, data) => {
  switch (command) {
    case "search": // 查询
      search();
      break;
    case "reset":
      reset();
      break;
    case "add":
      add();
      break;
    case "delet":
      deletUser(data);
      break;
    default:
      break;
  }
};
</script>
<template>
  <mangocrud
    ref="mangoref"
    :tableData="
      tableData.slice(
        (listConfig.pagination.page - 1) * listConfig.pagination.limit,
        listConfig.pagination.page * listConfig.pagination.limit
      )
    "
    :listConfig="listConfig"
    @handleAction="handleAction"
    @pagination-change="paginationchange"
  >
    <template #tool="scope">
      <el-button @click="toolFn(scope)">编辑</el-button>
    </template>
  </mangocrud>
  <el-dialog v-model="dialogVisible" title="title" width="50%" draggable>
    <searchForm
      ref="searchFormref"
      :forms="userlistCon.searchForm.forms"
      :isshowtool="false"
      :key="random"
    ></searchForm>
    <AutoNavi
      ref="AutoNaviref"
      :keyword="keyword"
      :modelRef="modelRef"
    ></AutoNavi>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="submitForm(ruleFormRef)"
          >submit</el-button
        >
      </span>
    </template>
  </el-dialog>
</template>

<style lang="scss">
</style>
